﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Fis.Web.Rules.Service
{

    public class DataBackupTask
    {
        System.Timers.Timer timer;

        public DataBackupTask(double interval)
        {
            timer = new System.Timers.Timer(interval * 1000);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        bool isLocked = false;
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isLocked)
                return;

            isLocked = true;

            var dc = Agile.Engine.Data.DataContext.Get("ServiceDataContext");
            var data = DataBackup.Config;

            //今天是否执行过

            var last = Agile.Engine.Utils.DataUtils.Parse(DateTime.MinValue, data.Rows[0]["FXTRA8"]);
            if (last.Month == DateTime.Now.Month && last.Day == DateTime.Now.Day)
            {
                isLocked = false;
                return;
            }


            DateTime timing = DateTime.Parse("0:00");
            if (!Agile.Engine.Utils.StringUtils.IsEmpty(data.Rows[0]["FXTRA7"]))
            {
                timing = DateTime.Parse(data.Rows[0]["FXTRA7"].ToString());
            }

            ///小时相等时执行
            if (DateTime.Now.Hour == timing.Hour)
            {
                DataBackup.Create(data).Backup();
                dc.DefaultModel.ExecuteNonQuery(
                    "UPDATE TXTRA SET FXTRA8=GETDATE() WHERE SID='" + DataBackup.DefaultConfig + "'");
            }

            isLocked = false;
        }
    }

    public class DataBackup
    {
        /// <summary>
        /// 指定配置的SID
        /// </summary>
        public readonly static string DefaultConfig = "_default_backup_";

        /// <summary>
        /// 数据库配置信息
        /// </summary>
        public static System.Data.DataTable Config
        {
            get
            {
                var dc = Agile.Engine.Data.DataContext.Get("ServiceDataContext");
                return dc.DefaultModel.QueryTable("TXTRA", "SID='" + DefaultConfig + "'");
            }
        }

        public static DataBackup Create(System.Data.DataTable data)
        {
            var target = data.Rows[0]["FXTRA1"].ToString();
            var source = Agile.Engine.Data.DataContext.Get("BaseDataContext").GetConnString;

            return new DataBackup()
            {
                SourceFolder = source
                ,
                TargetFolder = string.Format("{0}\\{1}\\", target, DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss"))
            };
        }

        /// <summary>
        /// 源文件夹
        /// </summary>
        public string SourceFolder { get; set; }
        /// <summary>
        /// 目标文件夹
        /// </summary>
        public string TargetFolder { get; set; }


        public void Backup()
        {
            BackupDirectory(new DirectoryInfo(SourceFolder));
        }


        void BackupDirectory(DirectoryInfo info)
        {
            foreach (var f in info.GetFiles().AsParallel())
            {
                var target = f.FullName.Replace(SourceFolder, TargetFolder);
                Agile.Engine.Utils.IOUtils.CreateDirectory(target);
                f.CopyTo(target, true);
            }

            foreach (var d in info.GetDirectories().AsParallel())
                BackupDirectory(d);
        }
    }
}
